package org.springboot.demo.controller;

import com.alibaba.fastjson.JSON;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springboot.demo.entity.Teacher;
import org.springboot.demo.service.TeacherDaoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/login")
public class LoginController {
    @Autowired
    private TeacherDaoService teacherDaoService;

    //登陆页面
    @RequestMapping("/main")
    public  String main(){
        return "main";
    }


    //登陆验证
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> login(HttpServletRequest request){
        String name=request.getParameter("t_Username");
        String password=request.getParameter("t_Password");

        Map<String,Object> map=new HashMap<>();
        // 令牌传入账号密码
        try{

            UsernamePasswordToken token=new UsernamePasswordToken(name,password);
            //创建 中心
            Subject subject = SecurityUtils.getSubject();
            //检测
            subject.login(token);
            //拿到正确的对象
            Teacher teacher= (Teacher) subject.getPrincipal();
            //获取session
            Session session = subject.getSession();
            session.setAttribute("admin",teacher);
        }catch (UnknownAccountException exception){
            System.out.println("账号出错");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            System.out.println("密码出错");
        }
        map.put("result",true);
        return map;

    }



    //进入首页
    @RequestMapping("/shouye")
    public String shouye(){
        return "shouye/shouye";
    }

    //菜单页面跳转
    @RequestMapping("/hraf")
    public String href(HttpServletRequest request){
        String hraf=request.getParameter("hraf");
        return hraf;
    }

}
